package com.maikang.exammall.service;

import com.maikang.exammall.entity.Comment;
import com.maikang.exammall.entity.OrderItem;
import com.maikang.exammall.entity.User;
import com.maikang.exammall.entity.UserContext;
import com.maikang.exammall.entity.constant.OrderStatus;
import com.maikang.exammall.entity.dto.SlicedContent;
import com.maikang.exammall.entity.dto.order.GroupedOrderItems;
import com.maikang.exammall.repository.CommentRepository;
import com.maikang.exammall.repository.CommissionRepository;
import com.maikang.exammall.repository.OrderItemRepository;
import com.maikang.exammall.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Log4j2
@Service
@RequiredArgsConstructor
public class CommentService extends BaseService<Comment, Long, CommentRepository> {
    private final OrderRepository orderRepository;
    private final OrderItemRepository orderItemRepository;
    private final CommissionRepository commissionRepository;


    @Transactional(rollbackFor = Exception.class)
    public Iterable<Comment> saveAll(List<GroupedOrderItems> groupedOrderItems) {
        User user = UserContext.getUser();
        List<Comment> comments = new ArrayList<>();
        List<Long> orderItemIds = new ArrayList<>();
        for (GroupedOrderItems group: groupedOrderItems) {
            Comment comment = Comment.builder().content(group.getCommentContent())
                    .pkgId(group.getPkgId())
                    .parentId(0L)
                    .pkgName(group.getPkgName())
                    .userId(user.getId())
                    .username(user.getUsername())
                    .userAvatarUrl(user.getAvatarUrl())
                    .build();
            comments.add(comment);

            orderRepository.findByIdAndUserIdAndInvisibleToUserAndStatus(group.getOrderId(), user.getId(), false, OrderStatus.EXAMINED_TO_COMMENT).ifPresent(order -> {
                order.setStatus(OrderStatus.COMMENTED);
                orderRepository.save(order);
            });
            for (OrderItem orderItem : group.getOrderItems()) {
                if (orderItem.getStatus().equals(OrderStatus.EXAMINED_TO_COMMENT)) {
                    orderItemIds.add(orderItem.getId());
                }
            }
        }
        orderItemRepository.updateStatusByIdsAndStatus(OrderStatus.EXAMINED_TO_COMMENT, OrderStatus.COMMENTED, orderItemIds);
        commissionRepository.updateStatusByOrderItemIds(orderItemIds, OrderStatus.COMMENTED);
        return repository.saveAll(comments);
    }

    public Iterable<Comment> findByPkgId(Long pkgId, Pageable pageable) {
        return new SlicedContent<>(repository.findByPkgIdOrderByCreatedDateDesc(pkgId, pageable));
    }
}
